package com.changan.parser;

import com.beust.jcommander.JCommander;
import com.beust.jcommander.ParameterException;

/**
 * @author wmh
 * @date 2021/7/26
 */
public class CliTool {
    /**
     * AppArgs appArgs = CliTool.getJcommander(AppArgs.class, args);
     *
     * @param clazz params class
     * @param args program class params
     * @param <T> app class type
     * @return params class
     */
    public static <T> T getJcommander(Class<T> clazz, String[] args) {
        JCommander jCommander = null;
        T paramsObj = null;
        try {
            paramsObj = clazz.newInstance();
            jCommander = JCommander.newBuilder().addObject(paramsObj).build();
            jCommander.parse(args);
        } catch (InstantiationException | IllegalAccessException e) {
            System.out.println("can't construct params class: " + clazz.getName());
        } catch (ParameterException e) {
            System.out.println(
                    "params parse error: \n" +
                            "your params is [" + String.join(" ", args) + "]\n" +
                            "Please follow the instructions below,thank you ^_^  :\n"
            );
            e.printStackTrace();
            if (jCommander != null) {
                jCommander.usage();
            }
            System.exit(0);
        }
        return paramsObj;
    }
}
